<?php

class Admin_model extends CI_Model {

    public function __construct() {
        parent::__construct();
        $this->load->library('encrypt');
    }

    /**
     * 登录检测
     * @param type $account
     * @param type $password
     */
    public function isAccount($account, $password) {
        $isAdmin = $this->is_unique($account);
        if ($isAdmin) {
            $query = $this->db->select('*')
                    ->where(array('admin_account' => $account))
                    ->get('admin');
            $result = $query->row();
            $encrypt_password = $this->encrypt->decode($result->admin_password);
            if ($password == $encrypt_password) {
                $this->session->set_userdata(array(
                    'is_login' => 1,
                    'uid' => $result->id,
                    'admin_account' => $result->admin_account,
                    'admin_auth' => $result->admin_auth,
                ));
                $this->db->where(array('id' => $result->id));
                $this->db->update('admin', array('admin_last_login' => time()));
                return TRUE;
            } else {
                return FALSE; //密码不正确
            }
        } else {
            return FALSE; //用户不存在
        }
    }

    /**
     * 检测用户名是否存在
     * @param type $account
     * @return type
     */
    public function is_unique($account) {
        $query = $this->db->get_where('admin', array('admin_account' => $account));
        $row = $query->num_rows();
        return $row == 0 ? FALSE : TRUE;
    }

    /**
     * 新增用户
     * @param array $data
     */
    public function add($data) {
        $data['admin_last_login'] = time();
        $this->db->insert('admin', $data);
    }

}
